//
//  FTImageView.m
//  FashionTech
//
//  Created by JackieYip on 2016/11/16.
//  Copyright © 2016年 mondial-d. All rights reserved.
//

#import "FTImageView.h"
#import "UIImageView+WebCache.h"

NSString *const kFTImageViewFTCacheLoadImageErrorKey = @"FTInheritLoadImageError";

@interface FTImageView ()
@property (strong, nonatomic, readwrite) NSError *FTInheritLoadImageError;

@end

@implementation FTImageView

- (void)ft_inherit_setImageWithURL:(NSURL *)URL placeholderImage:(UIImage *)image
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        SDWebImageOptions options = SDWebImageLowPriority | SDWebImageRetryFailed;
        // 检查缓存
        SDWebImageManager *manager = [SDWebImageManager sharedManager];
        BOOL didCache = [manager cachedImageExistsForURL:URL];
        // 已缓存
        if (didCache) {
            NSString *key = [manager cacheKeyForURL:URL];
            UIImage *image = nil;
            image = [manager.imageCache imageFromMemoryCacheForKey:key];
            if (!image)
                image = [manager.imageCache imageFromDiskCacheForKey:key];
            dispatch_async(dispatch_get_main_queue(), ^{
                self.image = image;
            });
        }
        // 未缓存
        else {
            self.alpha = 0.0f;
            __weak typeof(self) weakImageView = self;
            [self sd_setImageWithURL:URL placeholderImage:image options:options completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.FTInheritLoadImageError = error;
                });
                __strong typeof(weakImageView) strongImageView = weakImageView;
                [UIView animateWithDuration:0.5 animations:^{
                    strongImageView.alpha = 1.0f;
                }];
            }];
        }
    });
}

@end
